export default {
	// 为当前模块开启命名空间
	namespaced: true,
	// 模块的 state 数据
	state: () => ({
		// 购物车数组，用来存储购物车中每个商品的信息
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
	}),
	// 模块的 mutations 方法
	mutations: {
		addToCart(state, goods) {
			const result = state.cart.find(item => item.goods_id === goods.goods_id)
			if (result) {
				result.goods_count += 1
			} else {
				state.cart.push(goods)
			}
			this.commit('m_cart/saveToStorage')
		},
		updateGoodsState(state, goods) {
			const result = state.cart.find(item => item.goods_id === goods.goods_id)
			if (result) {
				result.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		updateGoodsCount(state, goods) {
			const result = state.cart.find(item => item.goods_id === goods.goods_id)
			if (result) {
				result.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		updateAllGoodsState(state, newState) {
			state.cart.forEach(item => item.goods_state = newState)
			this.commit('m_cart/saveToStorage')
		},
		// 将购物车中的数据持久化存储到本地
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	// 模块的 getters 属性
	getters: {
		// 统计购物车中商品的总数量
		total(state) {
			return state.cart.reduce((acc, curr) => acc + curr.goods_count, 0)
		},
		// 商品是否全部选中的状态
		isFullCheck(state) {
			let result = state.cart.every(goods => goods.goods_state === true)
			return result
		},
		totalPrice(state) {
			return state.cart.filter(goods => goods.goods_state === true).reduce((acc, item) => acc + item.goods_count *
				item
				.goods_price, 0).toFixed(2)
		},
		checkedCount(state) {
			const selectedGoods = state.cart.filter(goods => goods.goods_state === true)
			const accResult = selectedGoods.reduce((acc, item) => acc + item.goods_count, 0)
			return accResult
		}
	},
}
